package net.mikoo.seals.biz.manager;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import net.mikoo.seals.biz.mapper.DevicesMapper;
import net.mikoo.seals.biz.mapper.PartyMapper;
import net.mikoo.seals.biz.mapper.SealMapper;
import net.mikoo.seals.biz.mapper.StaffMapper;
import net.mikoo.seals.common.enums.DevicesStatusEnum;
import net.mikoo.seals.common.enums.SealStatusEnum;
import net.mikoo.seals.common.exception.ParametersException;
import net.mikoo.seals.model.Devices;
import net.mikoo.seals.model.DevicesQuery;
import net.mikoo.seals.model.Party;
import net.mikoo.seals.model.Seal;
import net.mikoo.seals.model.Staff;
import net.mikoo.seals.model.StaffQuery;

@Component
public final class SealManager {

	@Autowired
	private PartyMapper partyMapper;
	
	@Autowired
	private StaffMapper staffMapper;
	
	@Autowired
	private SealMapper sealMapper;
	
	@Autowired
	private DevicesMapper devicesMapper;
	
	public void validate(Seal seal) {
		
		if(seal == null){
			throw new IllegalArgumentException("seal");
		}
		
		if(seal.getCompanyId() == null) {
			throw new IllegalArgumentException("companyId");
		}
		
		if(StringUtils.isBlank(seal.getSealName())) {
			throw new ParametersException("印章名称不能为空");
		}
		
		if(seal.getPartyId() == null) {
			throw new ParametersException("印章管理员不能为空");
		}
		
		if(seal.getLimitUrgentApply() == null) {
			throw new ParametersException("最大紧急申请次数不能为空");
		}
	}
	
	public void save(Seal seal) {
		
		Party party = partyMapper.selectByPrimaryKey(seal.getPartyId());
		if(party == null) {
			throw new IllegalStateException("保管员信息不存在");
		}
		
		StaffQuery query = new StaffQuery();
		query.setCompanyId(seal.getCompanyId());
		query.setPartyId(seal.getPartyId());
		Staff staff = staffMapper.selectInfoByQuery(query);
		if(staff == null) {
			throw new IllegalStateException("保管员不是公司员工，无法设置");
		}
		
		if(StringUtils.isBlank(seal.getIsForcedPhoto())) {
			seal.setIsForcedPhoto("N");
		}
		seal.setCustosName(party.getPerson().getName());
		seal.setQuantity(0);
		seal.setApplyTimes(0);
		seal.setUseTimes(0);
		seal.setSealStatus(SealStatusEnum.DISABLE.getCode());
		seal.setCreateTime(new Date());
		sealMapper.insert(seal);
	}
}
